import $service from '../../../service.js';

var app = getApp();
Page({
  txTic: null,
  data: {
    isEsgin: $service.isEsgin,
    hospitalType: $service.hospitalType,
    autoplay: true,
    interval: 5000,
    duration: 500,
    currentTab: 0,
    currentIndex: 0,
    circular: true,
    indicatorDots: false,
    carouselActivityList: [], //轮播图
    active: true,
    prescriptionlist: [], //处方列表
    doctorInfo: {}, //医生详情
    inquiryLogListlength: 0, //候诊人数
    ullist: [], //问诊列表
    height: "",
    isReception: false, // 是否在接诊,
    receptionType: '', // 问诊方式
    typeList: [{
      name: '视频接诊',
      type: 1,
      img: '/static/images/icon_picture.png'
    }, {
      name: '图文接诊',
      type: 2,
      img: '/static/images/icon_video.png'
    }, {
      name: '图文+视频接诊',
      type: 3,
      img: '/static/images/icon_graphic_video.png'
    },{
      name: '自主开方',
      type: 4,
      img: '/static/images/icon_prescription_select.png'
    }],
    inquiryType: ''
  },
  onLoad(e) {
    //加载本页面的tabBar样式
    app.editTabBar();

  },
  async onShow() {
    wx.hideHomeButton({}),
      this.init();
    let receptionState = $service.getStore('isReception'); // 获取
    if (receptionState) {
      let type = await this.getDoctorDetail();
      this.receivePatients(type)
    }
  },
  init() {
    this.getDoctorOnlieConsultainfo();
    this.getBannerList();
    this.getConfigureName();
  },
  // 获取医生上一次接诊类型
  getDoctorDetail() {
    let {
      id
    } = JSON.parse($service.getStore('userInfo'))
    return app.http.getDoctorDetail({
      id: id
    }).then(res => {
      return res.data.inquiryType
    })
  },
  // 获取医生详情
  getDoctorOnlieConsultainfo() {
    app.http.getDoctorOnlieConsultainfo().then(res => {
      this.setData({
        doctorInfo: res.data
      })
      app.doctorId = res.data.id
    })
  },
  // 获取轮播图
  getBannerList() {
    app.http.getBannerList({}).then(res => {
      this.setData({
        carouselActivityList: res.data.list
      })
    })
  },
  //获取医院名称
  getConfigureName() {
    app.http.getConfigureName({}).then(res => {
      wx.setStorageSync('hospitalName', res.data.hospitalNameApp)
      wx.setNavigationBarTitle({
        title: res.data.hospitalNameApp,
        fail: (err) => {
          console.log(err);
        }
      })
    })
  },
  // webSocket 初始化
  initWebSocket() {
    app.webSocket.initWebSocket({
      url: $service.wsUrl
    });
    app.webSocket.onReceivedMsg(res => {
      if (res.packageType === 7) {
        if (res.isInquiry == 1) { // 如果有未结束的问诊 则弹窗询问
          this.reconnectModal(res)
        }
      }
    })
  },
  // 断线重连弹窗
  reconnectModal(e) {
    let {
      inquiryType,
      patientIM,
      id,
      doctorId,
      patientName,
      doctorIM,
      doctorName
    } = e.inquiryPatientInfoResp
    let logType;
    switch (inquiryType) {
      case '1':
        logType = '视频问诊';
        break;
      case '2':
        logType = '图文问诊';
        break;
      case '3':
        logType = '家庭医生问诊';
        break;
      case '4':
        logType = '复诊';
        break;
      default:
    }
    wx.showModal({
      cancelText: '不便接诊',
      confirmText: '重新连接',
      content: `您上一个"${logType}"还在进行中，患者仍在聊天室内等候您，请点击重新连接。`,
      success(res) {
        let params = {
          "logId": e.logId, //问诊id
          "patientIM": patientIM, //患者im
          "userId": id, //问诊id
          "packageMsg": "",
          "doctorName": doctorName,
          "doctorIM": doctorIM
        }
        if (res.confirm) {
          app.http.frozenOrder({
            logId: e.logId
          }).then(() => {
            params.packageType = 26
            app.webSocket.sendWebSocketMsg({
              data: params,
              success: () => {
                if (inquiryType == 1) {
                  $service.setStore('tencentConfigD', JSON.stringify(e.tencentConfig))
                }
                wx.reLaunch({
                  url: '/pages/chat/doctor_chat/doctor_chat?isAuto=0&logId=' + e.logId + '&imId=' + patientIM + '&inquiryPatientId=' + id + '&log_type=' + inquiryType + '&doctorId=' + doctorId + '&patientName=' + patientName + '&doctorIM=' + doctorIM
                })
              },
              fail: () => {
                $service.showToast('操作失败')
              }
            })
          })
        } else if (res.cancel) {
          app.http.unSuccessfulInquiry({
            id: e.logId
          }).then(res => {
            params.packageType = 25
            app.webSocket.sendWebSocketMsg({ // 医生发送结束问诊信息包
              data: {
                "logId": e.logId,
                "packageType": 13
              },
              success: () => {
                app.webSocket.sendWebSocketMsg({
                  data: params
                }) // 医生发送不方便重连信息包
              }
            })
          }).catch(err => {
            $service.showToast(err.msg)
          })
        }
      }
    })
  },
  // 暂停接诊
  stopReception() {
    wx.showModal({
      title: '您确定要暂停接诊吗？',
      content: '您确定要暂停接诊吗？暂停后已排队候诊的患者无法发起视频、图文问诊。请谨慎操作。',
      confirmColor: '#1189FF',
      success: (res) => {
        if (res.confirm) {
          app.http.receivePatients({
            "working": 0
          }).then(() => {
            this.setData({
              isReception: false
            })
            $service.removeStore('isReception')
            app.webSocket.closeWebSocket()
            app.globalData.ullist = []
            this.setData({
              ullist: []
            })
          }).catch(err => {
            $service.showToast(err.msg)
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 选择接诊类型
  async switchType(e) {
    let {
      type
    } = e.currentTarget.dataset
    wx.setStorageSync('type', type)
    if (type == 4) {
      app.http.getDoctorIncompleteInfo().then(res => {
        let url = res.data ? `/pages/chat/doctor_chat/doctor_chat?isAuto=1&logId=${res.data.logId}&inquiryPatientId=${res.data.patientId}` : '/pages/chat/doctor_chat/doctor_chat?isAuto=1'
        $service.openPage(url)
      }).catch(err => {
        $service.showToast(err.msg)
      })
    } else {
      let res = await app.http.getDoctorDetail({id: app.doctorId})
      let isReceive = false
      let resList = [{
        type: 1,
        enable: false
      },{
        type: 2,
        enable: false
      },{
        type: 3,
        enable: false
      },{
        type: 4,
        enable: false
      }]
      res.data.doctorPackageInfoResps.forEach((item, index) => {
        if (item.packageType == resList[index].type) {
          resList[index].enable = item.enable == 1 ? true : false
        }
      })
      // 是否开通了图文、家庭医生、复诊其中一个服务
      let txtService = resList[1].enable || resList[2].enable || resList[3].enable
      // 如开通了视频服务
      if (type == 1 && resList[0].enable) {
        isReceive = true
      }
      // 如开通了图文、家庭医生、复诊
      if (type == 2 && txtService) {
        isReceive = true
      }
      // 视频 + 图文
      if (type == 3 && resList[0].enable && txtService) {
        isReceive = true
      }
      if (isReceive) {
        wx.requestSubscribeMessage({
          tmplIds: $service.doctorTmplIds,
          complete: e => {
            console.log(e)
            this.receivePatients(type)
          }
        })
      } else {
        $service.showToast("暂未开启此服务，请联系管理员")
      }
    }
  },
  
  // 开始接诊
  receivePatients(type) {
    let parmas = {
      "inquiryType": type,
      "working": 1
    }
    this.initWebSocket()
    app.http.receivePatients(parmas).then((res) => {
      let receptionType = this.data.typeList.filter((i) => {
        return parmas.inquiryType == i.type
      })[0].name
      this.setData({
        isReception: true,
        receptionType,
        inquiryType: type
      })
      $service.setStore('isReception', 1) // 缓存接诊状态
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },


  inputChange(e) {
    if (e.detail.value != '') {
      $service.openPage('index_search/index_search?doctor_name=' + e.detail.value)
    }
  },
  gotopage(e) {
    var index = e.currentTarget.dataset.index;
    if (index == 0) { //我的消息
      $service.openPage('/pages/user_side/index/index_news/index_news')
    } else if (index == 1) { //网络问诊  
      $service.openPage('index_internet_interrogation/index_internet_interrogation')
    } else if (index == 2) { //网络问诊-医生值班
      $service.openPage('index_internet_interrogation/index_internet_interrogation?num=1')
    } else if (index == 3) { //我的用户
      $service.openPage('../my_users/my_users')
    } else if (index == 5) { //处方详情
      var num = e.currentTarget.dataset.num;
      $service.openPage('../../user_side/index/index_prescription_details/index_prescription_details?prescription_id=' + this.data.prescriptionlist[num].prescription_id)
    }
  }
})